#!/bin/bash

# 微服务启动脚本
# 作者: auth-cloud
# 日期: 2024-01-01

# 设置颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 项目根目录
PROJECT_ROOT=$(cd "$(dirname "$0")/.." && pwd)
echo -e "${GREEN}项目根目录: ${PROJECT_ROOT}${NC}"

# 检查Java环境
check_java() {
    if ! command -v java &> /dev/null; then
        echo -e "${RED}错误: 未找到Java环境，请先安装JDK 21${NC}"
        exit 1
    fi
    
    JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2 | cut -d'.' -f1)
    if [ "$JAVA_VERSION" -lt 21 ]; then
        echo -e "${RED}错误: Java版本过低，需要JDK 21或更高版本${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}Java环境检查通过: $(java -version 2>&1 | head -n 1)${NC}"
}

# 检查Maven环境
check_maven() {
    if ! command -v mvn &> /dev/null; then
        echo -e "${RED}错误: 未找到Maven环境，请先安装Maven${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}Maven环境检查通过: $(mvn -version | head -n 1)${NC}"
}

# 编译项目
build_project() {
    echo -e "${YELLOW}开始编译项目...${NC}"
    cd "$PROJECT_ROOT"
    
    if mvn clean package -DskipTests; then
        echo -e "${GREEN}项目编译成功${NC}"
    else
        echo -e "${RED}项目编译失败${NC}"
        exit 1
    fi
}

# 启动服务
start_service() {
    local service_name=$1
    local service_port=$2
    local jar_file=$3
    
    echo -e "${YELLOW}启动服务: ${service_name} (端口: ${service_port})${NC}"
    
    # 检查端口是否被占用
    if lsof -Pi :$service_port -sTCP:LISTEN -t >/dev/null; then
        echo -e "${RED}端口 ${service_port} 已被占用，请检查是否有其他服务在运行${NC}"
        return 1
    fi
    
    # 启动服务
    nohup java -jar "$jar_file" > "logs/${service_name}.log" 2>&1 &
    local pid=$!
    
    # 等待服务启动
    sleep 5
    
    # 检查服务是否启动成功
    if ps -p $pid > /dev/null; then
        echo -e "${GREEN}服务 ${service_name} 启动成功 (PID: ${pid})${NC}"
        echo $pid > "logs/${service_name}.pid"
    else
        echo -e "${RED}服务 ${service_name} 启动失败${NC}"
        return 1
    fi
}

# 停止服务
stop_service() {
    local service_name=$1
    local pid_file="logs/${service_name}.pid"
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null; then
            echo -e "${YELLOW}停止服务: ${service_name} (PID: ${pid})${NC}"
            kill $pid
            sleep 3
            
            if ps -p $pid > /dev/null; then
                echo -e "${RED}服务 ${service_name} 停止失败，强制杀死进程${NC}"
                kill -9 $pid
            fi
            
            echo -e "${GREEN}服务 ${service_name} 已停止${NC}"
        else
            echo -e "${YELLOW}服务 ${service_name} 未运行${NC}"
        fi
        rm -f "$pid_file"
    else
        echo -e "${YELLOW}服务 ${service_name} 未运行${NC}"
    fi
}

# 检查服务状态
check_service() {
    local service_name=$1
    local service_port=$2
    local pid_file="logs/${service_name}.pid"
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null; then
            if lsof -Pi :$service_port -sTCP:LISTEN -t >/dev/null; then
                echo -e "${GREEN}服务 ${service_name} 运行正常 (PID: ${pid}, 端口: ${service_port})${NC}"
                return 0
            else
                echo -e "${RED}服务 ${service_name} 进程存在但端口未监听${NC}"
                return 1
            fi
        else
            echo -e "${RED}服务 ${service_name} 进程不存在${NC}"
            return 1
        fi
    else
        echo -e "${RED}服务 ${service_name} 未运行${NC}"
        return 1
    fi
}

# 创建日志目录
create_logs_dir() {
    mkdir -p "$PROJECT_ROOT/logs"
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  start-all     启动所有服务"
    echo "  stop-all      停止所有服务"
    echo "  restart-all   重启所有服务"
    echo "  status        查看服务状态"
    echo "  build         编译项目"
    echo "  start [服务名] 启动指定服务"
    echo "  stop [服务名]  停止指定服务"
    echo "  help          显示帮助信息"
    echo ""
    echo "服务名:"
    echo "  gateway       网关服务 (端口: 8080)"
    echo "  registry      注册中心服务 (端口: 8081)"
    echo "  auth-service  认证服务 (端口: 8082)"
    echo "  user-service  用户服务 (端口: 8083)"
}

# 主函数
main() {
    create_logs_dir
    
    case "$1" in
        "start-all")
            check_java
            check_maven
            build_project
            
            echo -e "${YELLOW}启动所有服务...${NC}"
            start_service "gateway" 8080 "auth-gateway/target/auth-gateway-1.0.0.jar"
            start_service "registry" 8081 "auth-registry/target/auth-registry-1.0.0.jar"
            start_service "auth-service" 8082 "auth-service/target/auth-service-1.0.0.jar"
            start_service "user-service" 8083 "user-service/target/user-service-1.0.0.jar"
            
            echo -e "${GREEN}所有服务启动完成${NC}"
            ;;
        "stop-all")
            echo -e "${YELLOW}停止所有服务...${NC}"
            stop_service "user-service"
            stop_service "auth-service"
            stop_service "registry"
            stop_service "gateway"
            echo -e "${GREEN}所有服务已停止${NC}"
            ;;
        "restart-all")
            echo -e "${YELLOW}重启所有服务...${NC}"
            $0 stop-all
            sleep 5
            $0 start-all
            ;;
        "status")
            echo -e "${YELLOW}服务状态:${NC}"
            check_service "gateway" 8080
            check_service "registry" 8081
            check_service "auth-service" 8082
            check_service "user-service" 8083
            ;;
        "build")
            check_java
            check_maven
            build_project
            ;;
        "start")
            if [ -z "$2" ]; then
                echo -e "${RED}错误: 请指定服务名${NC}"
                show_help
                exit 1
            fi
            
            case "$2" in
                "gateway")
                    start_service "gateway" 8080 "auth-gateway/target/auth-gateway-1.0.0.jar"
                    ;;
                "registry")
                    start_service "registry" 8081 "auth-registry/target/auth-registry-1.0.0.jar"
                    ;;
                "auth-service")
                    start_service "auth-service" 8082 "auth-service/target/auth-service-1.0.0.jar"
                    ;;
                "user-service")
                    start_service "user-service" 8083 "user-service/target/user-service-1.0.0.jar"
                    ;;
                *)
                    echo -e "${RED}错误: 未知的服务名: $2${NC}"
                    show_help
                    exit 1
                    ;;
            esac
            ;;
        "stop")
            if [ -z "$2" ]; then
                echo -e "${RED}错误: 请指定服务名${NC}"
                show_help
                exit 1
            fi
            
            stop_service "$2"
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            echo -e "${RED}错误: 未知命令: $1${NC}"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
